
#define DS1302_READ 1
#define DS1302_RAM 0x20
#define DS1302_TIME 0x1F


void dly(){
  int volatile n;
  for(int i=0;i<1000;i++){
     n = i;
  }
}

int getCMOS(int index){
  IOWR(DS1302, DS1302_CS, 1);//cs
  //dly();
  IOWR(DS1302, DS1302_DATA, 0x80 | ((DS1302_RAM+index) << 1) | DS1302_READ);//send read time
  int val = IORD(DS1302, DS1302_DATA);
  IOWR(DS1302, DS1302_CS, 0);//cs
  return val;
}

int setCMOS(int index, int val){
  IOWR(DS1302, DS1302_CS, 1);//cs
  //dly();
  IOWR(DS1302, DS1302_DATA, 0x80 | ((DS1302_RAM+index) << 1));//send read time
  IOWR(DS1302, DS1302_DATA, val);
  IOWR(DS1302, DS1302_CS, 0);//cs
  return 0;
}

int getTime(char* datetime){
  IOWR(DS1302, DS1302_CS, 1);//cs
  //dly();
  IOWR(DS1302, DS1302_DATA, 0x80 | (DS1302_TIME << 1) | DS1302_READ);//send read time
  datetime[0] = IORD(DS1302, DS1302_DATA);
  datetime[1] = IORD(DS1302, DS1302_DATA);
  datetime[2] = IORD(DS1302, DS1302_DATA);
  datetime[3] = IORD(DS1302, DS1302_DATA);
  datetime[4] = IORD(DS1302, DS1302_DATA);
  datetime[5] = IORD(DS1302, DS1302_DATA);
  datetime[6] = IORD(DS1302, DS1302_DATA);
  datetime[7] = IORD(DS1302, DS1302_DATA);
  IOWR(DS1302, DS1302_CS, 0);//cs
}

int setTime(char* datetime){
  IOWR(DS1302, DS1302_CS, 1);//cs
  //dly();
  IOWR(DS1302, DS1302_DATA, 0x80 | (DS1302_TIME << 1));
  IOWR(DS1302, DS1302_DATA, datetime[0]);
  IOWR(DS1302, DS1302_DATA, datetime[1]);
  IOWR(DS1302, DS1302_DATA, datetime[2]);
  IOWR(DS1302, DS1302_DATA, datetime[3]);
  IOWR(DS1302, DS1302_DATA, datetime[4]);
  IOWR(DS1302, DS1302_DATA, datetime[5]);
  IOWR(DS1302, DS1302_DATA, datetime[6]);
  IOWR(DS1302, DS1302_DATA, datetime[7]);
  IOWR(DS1302, DS1302_CS, 0);//cs

}
